$(document).ready(function(){
	// get basic info and meassures for gallery:
	// nuber and size of thumbnails
	var numberOfThumbnails = $('.thumb_holder a').length;
	var thumbWidth = $('.thumb_holder a').outerWidth(true);
	var thumbHeight = $('.thumb_holder a').outerHeight(true);
	
	
	/*BEGIN*/
	// call function to adjust css styles
	// select first thumbnail and show midsized image
	cssStuff();

	// click on thumbnail -> load midsized image
	$('.thumb_holder a').each(function(){
		$(this).click(function(event){
			event.preventDefault();
			$(this).parent().children('.selected').removeClass('selected');
			$(this).addClass('selected');
			$('.img_holder').children().fadeOut(300, function(){showMidsize();});
		});
	});
		
	// thumbnail navigation slider
	$('.thumb_nav .prev').click(function(){
		if( $('.thumb_holder a').is(':animated') ) {return false} else {
			var firstThumbPos = $('.thumb_holder a:first').position().left;
			if (firstThumbPos==0) {dissableNav();}
			else {$('.thumb_holder a').animate({'left': "+="+thumbWidth+'px'},200,function(){dissableNav()});};
		}
	});
	
	$('.thumb_nav .next').click(function(){
		if( $('.thumb_holder a').is(':animated') ) {return false} else {
			var lastThumbPos = $('.thumb_holder a:last-child').position().left;
			var lastThumbSpace = $('.thumb_wrapper').width()-thumbWidth;
			if (lastThumbPos<=lastThumbSpace) {dissableNav();}
			else {$('.thumb_holder a').animate({'left': "-="+thumbWidth+'px'},200,function(){dissableNav()});};
		}
	});
	
	
	// IMAGE TOOLS
	// gallery background
	$('.gallery_bgr a').click(function(event){
		event.preventDefault();
		var bgrCol = $(this).css('background-color');
		$('.img_wrapper .img_holder').css('background-color',bgrCol);
	});
	
	//flip image
	$('.flip_img').click(function(event){
		event.preventDefault();
		$('.img_holder a').toggleClass('flip-h');
	});
	
	//black-white image
	$('.bw_img').click(function(event){
		event.preventDefault();
		$('.img_holder img').clone().hide().appendTo('.img_holder');
		$('.img_holder a img').pixastic("desaturate");
		$(this).hide();
		$('.col_img').css('display','inline-block');
	});
	
	//color image
	$('.col_img').click(function(event){
		event.preventDefault();
		$('.img_holder a').children().remove();
		$('.img_holder>img').appendTo('.img_holder a');
		//$('.img_holder>img').remove();
		$('.img_holder img').show();
		$(this).hide();
		$('.bw_img').show();
	});
	
	//crop image
	$('.img_holder a').live('click',function(event){event.preventDefault();});
	
	$('.crop_img').click(function(event){
		event.preventDefault();
		$('.img_holder a').imgAreaSelect({
			x1:325, y1:100, x2:425, y2:180,
			onInit:function(){
				disable=true,
				enable=true,
				cropImgUpdate
			},
			onSelectEnd:cropImgUpdate
		});
		
	});
	
	$('.mark_area').click(function(event){
		var markArea = $(this).attr('href');
		var markAreaCoor = markArea.split(',');
		event.preventDefault();
		$('.img_holder a').imgAreaSelect({
			x1:markAreaCoor[0],
			y1:markAreaCoor[1],
			x2:markAreaCoor[2],
			y2:markAreaCoor[3],
			onInit:function(){
				disable=true,
				enable=true,
				cropImgUpdate
			},
			onSelectEnd:cropImgUpdate
		});
	});
	
	function cropImgUpdate(img, selection) {
		$('.ins_area').attr('href', selection.x1+','+selection.y1+','+selection.x2+','+selection.y2);            
	};
	
	//full screen image
	$('.full_img').click(function(event){
		event.preventDefault();
		var winTarget = $('.img_holder a').attr('href');
		settings = 'height='+screen.height+',width='+screen.width+',top=0,left=0';
		window.open(winTarget,'Tattooportal.org - Uvećana slika',settings);
	});
	
	

	
	// GALLERY FUNCTIONS
	function cssStuff(){
		// adjust thumbnails position to absolute, calculate and set thumb_holder width
		$('.thumb_holder').css({
			'width': (numberOfThumbnails*thumbWidth)+'px',
			'height': thumbHeight+'px'
		});
		$('.thumb_holder a').css({'position':'absolute'});
		for (var i=0;i<=numberOfThumbnails;i++){
			$('.thumb_holder a').eq(i).css({
				'left': (i*thumbWidth)+'px'
			})	
		};
		dissableNav();
	};
	
	
	function showMidsize(){
		// takes selected thumbnail's attribute href and loads image in img_holder
		// takes selected thumbnail's image longdesc attribute for displaying zoom image
		var midImagePath = $('.thumb_holder a.selected').attr('href');
		var zoomImagePath = $('.thumb_holder a.selected').children('img').attr('longdesc');
		
		$('.img_holder').children().remove();
		$('.img_holder').addClass('loading');
		
		var preloadImg = new Image();
		$(preloadImg)
			.load(function(){
				$(this).hide();
				$('.img_holder').removeClass('loading');
				$('.img_holder').html('<a href="'+zoomImagePath+'"></a>');
				$('.img_holder a').append(this);
				$(this).fadeIn();
				dissableNav();
				linksUpdate();
			})
			.error(function(){
				$('.img_holder').removeClass('loading');
				$('.img_holder').html('<p style="font-size:14px; text-align:center; margin-top:40px">Veća slika nije pronađena. Izvinjavamo se.</p>');
			})
			.attr('src',midImagePath);
               var photo_id = $('.thumb_holder a.selected').attr('id');
               getComments(photo_id);
               incrementImageViews(photo_id);
               addHiddenPhotoId(photo_id);

	};
	
	function linksUpdate(){
		var lnkTarget = $('.img_holder a').attr('href');
		$('.imgLnkPath').text(lnkTarget);
		$('.fb_img').attr('href','http://www.facebook.com/sharer.php?u='+lnkTarget);
	};

	
	function dissableNav(){
		//left thumnails navigation dissable
		var firstThumbPos = $('.thumb_holder a:first').position().left;
		if (firstThumbPos==0) {$('.thumb_nav .prev').addClass('dissabled')}
		else {
			if ($('.thumb_nav .prev').hasClass('dissabled')){$('.thumb_nav .prev').removeClass('dissabled')}
		};
		
		//right thumnails navigation dissable
		var lastThumbPos = $('.thumb_holder a:last-child').position().left;
		var lastThumbSpace = $('.thumb_wrapper').width()-thumbWidth;
		if (lastThumbPos<=lastThumbSpace) {$('.thumb_nav .next').addClass('dissabled')}
		else {
			if ($('.thumb_nav .next').hasClass('dissabled')){$('.thumb_nav .next').removeClass('dissabled')}
		};
		
		
		//prev image navigator disable
		if ($('.thumb_holder .selected').is(':first-child')){$('.img_nav .prev').hide();}
		else {$('.img_nav .prev').show();};
		
		//next image navigator disable
		if ($('.thumb_holder .selected').is(':last-child')){$('.img_nav .next').hide();}
		else {$('.img_nav .next').show();};
		
	};
	
	function getComments(photo_id) {
            $.post("handlers/hgalerija_single.php", {
                action: 'img_params',
                photo_id: photo_id
            },
            function(res){
                $('#comments ul').html(res.comments);
                var commentsCount = $('#comments li').length;
                $('#comments > p span').html(commentsCount);
                //Populate image info
                var image=res.image;
                $('.imgAuthor a').html(image.username);
                $('.imgName').html(image.naziv);
                $('.imgGallery').html(image.galerija);
                $('.imgTags').html(image.kljucne_reci);
                $('.imgDate').html(image.datum_postavljanja);
                $('.imgViews').html(image.broj_pregleda);
                $('.imgLikes').html(image.broj_skljoceva);
                $('.imgAuthorComment').html(image.opis);
            },
        'json');
        }

        function addHiddenPhotoId(photo_id) {
            $('#photo_id').val(photo_id);
        }

        function incrementImageViews(photo_id) {
            $.post("handlers/hgalerija_single.php", {
                action: 'view',
                photo_id: photo_id
            });
        }

        function setLike() {
            var photo_id = $('.thumb_holder a.selected').attr('id');
            $.post("handlers/hgalerija_single.php", {
                action: 'like',
                photo_id: photo_id
            },
            function() {
                alert("Vaš Like je uspešno upisan");
            }
        );
        }

        $('.like_img').click(function(){
            setLike();
            $('.like_img').unbind('click');
        });
	
});